/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uni.j2ee.forum.ejb.impl;

import java.util.List;
import javax.ejb.Stateless;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import uni.j2ee.forum.model.ForumPost;
import uni.j2ee.forum.model.ForumTopic;

/**
 *
 * @author ivan
 */
@Stateless

public class ForumPostFacade extends AbstractFacade<ForumPost> {
    @PersistenceContext(unitName = "SimpleForumJSF")
    private EntityManager em;

    
    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ForumPostFacade() {
        super(ForumPost.class);
    }
    
    public List<ForumPost> findPostsInTopic(ForumTopic topic, int from, int to) {
      final TypedQuery<ForumPost> q = 
              getEntityManager().createNamedQuery("ForumPost.findByTopicId", ForumPost.class)
                    .setParameter("topicId", topic);
      q.setMaxResults(to - from);
      q.setFirstResult(from);
      return q.getResultList();
    }
    
    public int count(ForumTopic topic) {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
        javax.persistence.criteria.Root<ForumPost> rt = cq.from(ForumPost.class);
        cq.select(cb.count(rt));
        Predicate pred = cb.equal(rt.get("topicId"), topic);
        cq.where(pred);
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }
            
}
